package me.yangteng.zhihudaily.fragment;


import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONObject;
import org.json.XML;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import me.yangteng.zhihudaily.R;
import me.yangteng.zhihudaily.model.Weather;
import me.yangteng.zhihudaily.util.HttpLoader;
import me.yangteng.zhihudaily.util.Url;

/**
 * A simple {@link Fragment} subclass.
 */
public class WeatherForecastFragment extends Fragment {
  private static final String TAG = "WeatherForecastFragment";
  private Gson gson;
  private View view;
  private Context context;
  private String cityName;
  private Weather weather;
  private TextView cityNameText, weatherNameText, temperatureText;
  private Calendar calendar;
  private SimpleDateFormat simpleDateFormat;

  public WeatherForecastFragment() {
    // Required empty public constructor
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    gson = new Gson();
    cityName = "广州";
    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("HH", new Locale(Locale.CHINESE.getLanguage()));
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    Log.d(TAG, "ForecastFragment on create view");
    // Inflate the layout for this fragment
    this.view = inflater.inflate(R.layout.fragment_weather_forecast, container, false);
    context = getContext();

    cityNameText = view.findViewById(R.id.weatherCityName);
    weatherNameText = view.findViewById(R.id.weatherWeatherName);
    temperatureText = view.findViewById(R.id.weatherTemperature);
    getLocation();
    return view;
  }


  private void getLocation() {
    HttpLoader httpLoader = new HttpLoader();
    httpLoader.setHttpLoaderListener(new HttpLoader.HttpLoaderListener() {
      @Override
      public void onGetHttpString(String string) {
        try {
          JSONObject location = XML.toJSONObject(string, true);
          if (location.getJSONObject("response").getInt("status") == 1) {
            Log.d(TAG, location.toString());
            cityName = location.getJSONObject("response").getString("city");
          }
        } catch (Exception e) {
          Log.d(TAG, e.toString());
          e.printStackTrace();
        } finally {
          getWeather();
        }
      }

      @Override
      public void onError(Exception e) {
        HttpLoader.onErrorHandler(view);
      }
    });
    httpLoader.execute(Url.GET_LOCATION + this.getString(R.string.amap_web_api_key));
  }

  private void getWeather() {
    try {
      HttpLoader httpLoader = new HttpLoader();
      httpLoader.setHttpLoaderListener(new HttpLoader.HttpLoaderListener() {
        @Override
        public void onGetHttpString(String string) {
          try {
            JSONObject location = XML.toJSONObject(string, true).getJSONObject("resp");
            if (!location.has("error")) {
              weather = gson.fromJson(location.toString(), Weather.class);
              renderWeather();
            } else {
              cityName = "广州";
              getWeather();
            }
          } catch (Exception e) {
            Log.d(TAG, e.toString());
          }
        }

        @Override
        public void onError(Exception e) {
          HttpLoader.onErrorHandler(view);
        }
      });
      httpLoader.execute(Url.GET_WEATHER + this.cityName);
    } catch (Exception e) {
      e.printStackTrace();
      Log.d(TAG, e.toString());
    }

  }

  private void renderWeather() {
    cityNameText.setText(cityName);

    int currentHour = Integer.parseInt(simpleDateFormat.format(calendar.getTime()));
    if (currentHour > 6 && currentHour < 18) {
      weatherNameText.setText(weather.getForecast().getWeather().get(0).getDay().getType());
    } else {
      weatherNameText.setText(weather.getForecast().getWeather().get(0).getNight().getType());
    }

    temperatureText.setText(weather.getWendu() + "" + getString(R.string.degree_text));
  }
}
